<?php

namespace App\Http\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;


class UserThirdpart extends Base
{
    protected $table = 'user_thirdpart';
    public $timestamps = false;
    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }
    
    public function checkThirdUser($condition,$fields){
        $result = $this->getSingle($condition,$fields);
        if(isset($result[0])){
            return $result[0];
        }else{
            return [];
        }
    }
    
    public function addThirdUser($data){
        return $this->insertSingle($data);
    }
    
    public function updateThirdUser($condition,$data){
        return $this->singleUpdate($condition,$data);
    }
    
    public function getThirdUser($condition)
    {
        $document = DB::table($this->table)->where($condition)->get();
        return self::objToArray($document);
    }


    /**
     * 设置用户ID
     * @param $openId
     * @param $source
     * @param $userId
     */
    public function setUserId($openId, $source, $userId){
        DB::table($this->table)
            ->where('openid', '=', $openId)
            ->where('source', '=', $source)
            ->where('user_id', '=', 0)
            ->update([
                'user_id' => $userId
            ]);
    }

    /**
     * 更新union_id
     * @param $openId
     * @param $source
     * @param $unionId
     */
    public function setUnionId($openId, $source, $unionId){
        DB::table($this->table)
            ->where('openid', '=', $openId)
            ->where('source', '=', $source)
            ->update([
                'unionid' => $unionId
            ]);
    }

    /**
     * 获取第三方信息
     * @param $openid
     * @param $source
     * @return mixed|null
     */
    public function get_third($openid, $source){
        $third = DB::table($this->table)
            ->where(['openid' => $openid, 'source' => $source])
            ->first(['id', 'openid', 'unionid', 'user_id', 'platform_type', 'create_timestamp', 'source', 'portrait', 'nickname']);
        if (empty($this)){
            return null;
        }
        return self::objToArray($third);
    }

    /**
     * 获取第三方信息
     * @param $unionId
     * @param $source
     * @return mixed|null
     */
    public function getThirdByUnion($unionId, $source){
        $third = DB::table($this->table)
            ->where(['unionid' => $unionId, 'source' => $source])
            ->where('user_id', '<>', 0)
            ->where('unionid', '<>', '')
            ->first(['id', 'openid', 'unionid', 'user_id', 'platform_type', 'create_timestamp', 'source', 'portrait', 'nickname']);
        if (empty($third)){
            return null;
        }
        return self::objToArray($third);
    }
    
}
